package com.tsingteng.cosfun.ui.setting;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BaseFragment;
import com.tsingteng.cosfun.bean.BaseDataBean;
import com.tsingteng.cosfun.bean.ImgBean;
import com.tsingteng.cosfun.bean.PersonBean;
import com.tsingteng.cosfun.bean.VideoSignBean;
import com.tsingteng.cosfun.crashUtils.utils.ExceptionUpLoader;
import com.tsingteng.cosfun.ui.cosfun.adapter.TipOffsImgAdapter;
import com.tsingteng.cosfun.ui.cosfun.contract.FeedBackContract;
import com.tsingteng.cosfun.ui.cosfun.presenter.FeedbackPresenter;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.PhotoUtils;
import com.tsingteng.cosfun.utils.ToastUtils;
import com.tsingteng.cosfun.utils.UploadBitmapUtil;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.TagsGridView;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;



/**
 * author :zhikuan
 * Date:18-8-10
 */
public class FeedbackFragment extends BaseFragment implements View.OnClickListener, TipOffsImgAdapter.ImgOnClickListener, FeedBackContract.IfeedBackView {

    TipOffsImgAdapter tipOffsImgAdapter = null;
    TagsGridView tagsGridView = null;

    List<ImgBean> list = new ArrayList<>();
    private TextView mTextCount;
    private EditText mEditText, phoneEdit;
    private final int COUNT_MAX = 200;

    private FeedbackPresenter feedbackPresenter;

    @Override
    protected void initView() {

        mTextCount = rootView.findViewById(R.id.text_count);
        mEditText = rootView.findViewById(R.id.advices);
        phoneEdit = rootView.findViewById(R.id.phone_num);
        tagsGridView = rootView.findViewById(R.id.feedback_imggrid);
        handleImg("");
        tipOffsImgAdapter = new TipOffsImgAdapter(getActivity(), getActivity(), list, this);
        tagsGridView.setAdapter(tipOffsImgAdapter);
        feedbackPresenter = new FeedbackPresenter(this);
        onInitListenr();
            ExceptionUpLoader.getmInstance().upLoadCrashLog(new ExceptionUpLoader.ExceptionUpLoadListener() {
                @Override
                public void exceptionSuccess() {
                }

                @Override
                public void exceptionFail() {
                }
            });
    }

    private void onInitListenr() {
        mEditText.addTextChangedListener(new TextWatcher() { //对EditText进行监听
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                mTextCount.setText((COUNT_MAX - editable.length()) + "/" + COUNT_MAX);
            }
        });
        rootView.findViewById(R.id.apply).setOnClickListener(this);
        rootView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                hideSoftInput(view.getWindowToken());
                return false;
            }
        });
    }

    /**
     * 判定当前是否需要隐藏
     */
    protected boolean isShouldHideKeyBord(View v, MotionEvent ev) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            return !(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom);
        }
        return false;
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager manager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    @Override
    protected void getBundle(Bundle bundle) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_setting_feedback_layout;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.apply:
                if (TextUtils.isEmpty(mEditText.getText().toString())) {
                    ToastUtils.showToast("请留下您的宝贵意见");
                    return;
                }
                if (list.size() == 0) {
                    ToastUtils.showToast("图片未添加");
                    return;
                }

                String img = "";
                for (ImgBean imgBean : list) {
                    if (imgBean.getType() == 1) {
                        if (TextUtils.isEmpty(img)) {
                            img = imgBean.getPath();
                        } else {
                            img = img + "," + imgBean.getPath();
                        }
                    }
                }
                feedbackPresenter.feedback(mEditText.getText().toString(), img, phoneEdit.getText().toString(), "");
                break;

        }
    }


    private Uri imageUri = null;


    /**
     * 图片选择及拍照结果
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case PhotoUtils.CODE_GALLERY_REQUEST:// 相册
                if (data == null) {
                    return;
                }
                imageUri = Uri.parse(PhotoUtils.getPath(getActivity(), data.getData()));
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                    imageUri = FileProvider.getUriForFile(getActivity(), PhotoUtils.AUTH, new File(imageUri.getPath()));
//                }
                feedbackPresenter.getSignTureData("1");
                break;
            case PhotoUtils.CODE_CAMERA_REQUEST:// 拍照
                feedbackPresenter.getSignTureData("1");
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case PhotoUtils.CAMERA_PERMISSIONS_REQUEST_CODE: {//调用系统相机申请拍照权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.takePicture(getActivity(), imageUri, PhotoUtils.CODE_CAMERA_REQUEST);
                } else {
                    ToastUtils.showToast("请允许打开相机！！");
                }
                break;

            }
            case PhotoUtils.STORAGE_PERMISSIONS_REQUEST_CODE://调用系统相册申请Sdcard权限回调
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(getActivity(), PhotoUtils.CODE_GALLERY_REQUEST);
                } else {
                    ToastUtils.showToast("请允许打操作SDCard！！");
                }
                break;
        }
    }

    @Override
    public void add() {
        File file = new File(VideoUtils.photoSavePathCache, System.currentTimeMillis() + ".png");
        if (PhotoUtils.hasSdcard()) {
            imageUri = Uri.fromFile(file);
            //通过FileProvider创建一个content类型的Uri
         /*   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(getActivity(), PhotoUtils.AUTH, file);
            }*/
            PhotoUtils.getInstance().showPopupWindow(getActivity(), rootView, imageUri);
        } else {
            ToastUtils.showToast("设备没有SD卡！");
        }

    }

    @Override
    public void del(int index) {
        delImg(index);
    }

    public void handleImg(String url) {
        if (list == null) {
            return;
        }
        for (ImgBean imgBean : list) {
            if (imgBean.getType() == 0) {
                list.remove(imgBean);
                break;
            }
        }
        if (list.size() == 4) {
            return;
        }
        if (!TextUtils.isEmpty(url)) {
            ImgBean imgBean = new ImgBean();
            imgBean.setType(1);
            imgBean.setPath(url);
            list.add(imgBean);
        }
        if (list.size() < 4) {
            ImgBean imgBean = new ImgBean();
            imgBean.setType(0);
            list.add(imgBean);
        }
        if (tipOffsImgAdapter != null)
            tipOffsImgAdapter.notifyDataSetChanged();
    }

    public void delImg(int index) {
        if (list == null) {
            return;
        }
        for (ImgBean imgBean : list) {
            if (imgBean.getType() == 0) {
                list.remove(imgBean);
                break;
            }
        }
        list.remove(index);

        if (list.size() < 4) {
            ImgBean imgBean = new ImgBean();
            imgBean.setType(0);
            list.add(imgBean);
        }

        if (tipOffsImgAdapter != null)
            tipOffsImgAdapter.notifyDataSetChanged();
    }

    @Override
    public void onSuccess(BaseDataBean<PersonBean> personBeanBaseDataBean) {
        if (personBeanBaseDataBean.getStatus() == 200) {
            ToastUtils.showToast("提交成功");
            getActivity().finish();
        }
    }

    @Override
    public void UploadVideo(VideoSignBean data) {
        String pathCompress = VideoUtils.photoSavePathCache + System.currentTimeMillis() + ".png";
        int state = UploadBitmapUtil.compress(PhotoUtils.getRealPathFromURI(getActivity(), imageUri), pathCompress, UploadBitmapUtil.SMALL_IMAGE_COMPRESS);
        if (state == UploadBitmapUtil.SUCCESS) {
            // 显示进度条
            UploadManager uploadManager = new UploadManager();
            uploadManager.put(pathCompress,
                    String.valueOf(LogonUtils.getProFildId() + System.currentTimeMillis()).

                            hashCode() + data.getPath(),
                    data.getSign(), new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject response) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (info.isOK()) {
                                        ToastUtils.showToast("上传成功");
//                                        String path = PhotoUtils.URL_IMG + "/" + key;
                                        String path = data.getDomain() + "/" + key;
                                        ;
                                        handleImg(path);
                                    } else {
                                        ToastUtils.showToast(info.error);
                                    }
                                }
                            });

                        }
                    }, null);

        } else if (state == UploadBitmapUtil.FILE_NOT_FOUND) {
            ToastUtils.showToast("文件夹找不到");
        } else if (state == UploadBitmapUtil.GEN_BITMAP_FAILURE) {
            ToastUtils.showToast("生成图像失败");
        } else if (state == UploadBitmapUtil.IO_EXCEPTION) {
            ToastUtils.showToast("存储文件失败");
        }
    }


    @Override
    public void showLoading(String msg) {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        hideLoadingDialog();
    }

    @Override
    public void showFail(String msg) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showEmpty() {

    }
}
